<template>
  <div>
    <AMap :markers="markers" :rightActions="rightActions" search searchPosition="inside" ref="amapRef" />
    <!--引用表格-->
    <BasicTable @register="registerTable" @row-click="handleRowClick">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!-- <a-button class="xinzeng" type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <template #plotTotal="{ record }">
        <router-link :to="{
          path: '/basic-information/region',
          query: { baseid: record.id }
        }">
          {{ record.plotTotal }}
        </router-link>
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{ text }">
        {{ getAreaTextByCode(text) }}
      </template>

      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small"
          @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <TBaseModal @register="registerModal" @success="handleSuccess"></TBaseModal>
  </div>
</template>

<script lang="ts" name="base-tBase" setup>

import AMap from '/@/components/AMap/AMap1.vue'
import { ref, nextTick } from 'vue';
import { useRouter } from "vue-router";

import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import TBaseModal from './components/TBaseModal.vue'
import { columns, searchFormSchema } from './TBase.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './TBase.api';
import { downloadFile } from '/@/utils/common/renderUtils';
// import { otherHttp } from "/@/utils/http/axios";
// import {message} from "ant-design-vue";
const markers = ref<any>([]);
const amapRef = ref();
// const checkedKeys = ref<Array<string | number>>([]);
// 路由
const router = useRouter();
//注册model
const [registerModal, { openModal }] = useModal();
//注册table数据

const handleRowClick = (row, index, event) => {
  amapRef.value.setCenter([row.longitude, row.latitude])
}

const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '基地',
    api: (args) => new Promise((resolve, reject) => {
      list(args).then(res => {
        nextTick(() => {
          markers.value = res.records.map((record) => {
            const { name, poi, latitude, picture, longitude } = record;
            return {
              name, address: poi, lnglat: [longitude, latitude], img: picture, onClick() {
                handleEdit(record);
              }
            }
          }
          )
        })
        resolve(res);
      }).catch(reject)
    }),
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
  },
  exportConfig: {
    name: "基地",
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})

const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext

const rightActions = [
  {
    name: '新增基地', handler(e: { lng: any; lat: any; }) {
      // otherHttp.get({
      //   url: '/v3/geocode/regeo',
      //   params: {
      //     key: '01b37de61ae67108b5ebae705170f5aa',
      //     location: [e.lng, e.lat].join(',')
      //   }
      // }).then(res => {
      //   if (parseInt(res.status)) {
      //     handleAdd({
      //       poi: res.regeocode.formatted_address,
      //       lnglat: [e.lng, e.lat]
      //     })
      //   } else {

      //   }
      // }).catch(err => {
      //   console.log(err)
      // })
      amapRef.value.refreshAddress([e.lng, e.lat]).then(res => {
        handleAdd({
          poi: res,
          lnglat: [e.lng, e.lat]
        })
      }).catch(err => {
        console.log(err)
      })
    }
  },
];

/**
 * 新增事件
 */
function handleAdd(poi: { poi: any; lnglat: any; }) {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
    poi: poi
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 地块
 */
function handlePlot(record: Recordable) {
  // 跳转到地块，并且携带参数
  router.push({
    path: '/basic-information/region',
    query: { baseid: record.id }
  });

}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
// async function batchHandleDelete() {
//   await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
// }
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    }
  ]
}
/**
   * 下拉操作栏
   */
function getDropDownAction(record) {
  let rs =
    [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '管理地块',
        onClick: handlePlot.bind(null, record),
      }

    ]
  if (record.plotTotal === 0) {

    rs.push({
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      }
    })

  }
  return rs;
}


</script>

<style scoped>
.xinzeng {
  position: absolute;
  top: -60px;
  right: 34px;
}

:deep(.jeecg-basic-table-form-container .ant-form) {
  display: none;
}
</style>
